package com.dynamic.config;

import com.dynamic.enums.ErrorEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

	@Bean
	public Docket createRestApi() {
		//添加全局响应状态码
		List<ResponseMessage> responseMessageList = new ArrayList<>();
		Arrays.stream(ErrorEnum.values()).forEach(errorEnum -> {
			responseMessageList.add(
					new ResponseMessageBuilder().code(errorEnum.getCode()).message(errorEnum.getMsg()).responseModel(
							new ModelRef(errorEnum.getMsg())).build()
			);
		});

		return new Docket(DocumentationType.SWAGGER_2)
				// 添加全局响应状态码
				.globalResponseMessage(RequestMethod.GET, responseMessageList)
				.globalResponseMessage(RequestMethod.POST, responseMessageList)
				.globalResponseMessage(RequestMethod.PUT, responseMessageList)
				.globalResponseMessage(RequestMethod.DELETE, responseMessageList)
				.apiInfo(apiInfo())
				.select()
				//加了ApiOperation注解的类，才生成接口文档
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.paths(PathSelectors.any())
				.build()
				.directModelSubstitute(java.util.Date.class, String.class);

	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("客服系统API")
				.description("客服系统PI服务接口文档")
				.termsOfServiceUrl("https://www.call.com")
				.version("1.0.0")
				.build();
	}
}